// pages/order/index.js
const app = getApp()
const wxpay = require('../../utils/pay.js')
const dateUtil = require('../../utils/date.js')
const CONFIG = require('../../config.js')
const WXAPI = require('../../wxapi/main')
const CryptoJS = require('../../utils/crypto.js')

import drawQrcode from '../../utils/weapp.qrcode.min.js'
import Toast from 'tdesign-miniprogram/toast/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderDetail: {},
    userInfo: {},
    orderMethodMap: {
      0: "线上支付",
      1: "线下支付",
      4: "余额支付"
    },
    paymentVenueMap: {
      "1": "开通会员",
      "2": "预约",
      "3": "机位结算"
    },
    statusMap: {
      '0': '初始化',
      '1': '未付款',
      "2": "已支付",
      "3": "已取消",
      "4": "发起退款",
      "5": "已退款",
    },
    canUseCoupons: [],
    coupons_current_no: 0,
    coupons_page_size: 1,
    isLastPage: false,
    couponVisible: false,
    use_coupon: '',
    //选择框选中的
    selectedCoupon: {},
    //选中后确认的
    confirmCoupon: {},
    interval: null,
    useRecharge: false,
  },
  async changeAmount(event) {

    try {
      if (!event.detail.value || event.detail.value == '')
        return;
      const res = await wx.showModal({
        title: '确认',
        content: `实际金额:${this.data.orderDetail.amount}变更为：${event.detail.value}`
      })
      if (res.confirm) {
        this.updateOrder({ amount: event.detail.value })
      } else if (res.cancel) {
        return;
      }
    } catch (e) {
      console.error(e)
    }
  },
  updateOrder(param) {

    var { order_no } = this.data.orderDetail;
    WXAPI.updateOrder(order_no, param).then(res => {
      if (res.order_no) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: "更新成功",
          theme: 'success',
          direction: 'column',
        });
      }

      return
    })
  },
  async changeMemo(event) {

    try {
      if (!event.detail.value || event.detail.value == '')
        return;
      const res = await wx.showModal({
        title: '确认',
        content: `修改备注为:${event.detail.value}`
      })
      if (res.confirm) {
        this.updateOrder({ memo: event.detail.value })
        var orderDetail = this.data.orderDetail
        orderDetail.memo = event.detail.value
        this.setData({
          orderDetail
        })
      } else if (res.cancel) {
        return;
      }
    } catch (e) {
      console.error(e)
    }
  },
  payByManger(e) {

    var data = this.data.orderDetail
    var type = e.currentTarget.dataset.index;

    //线上
    if (type == 0) {
      var content = "/pages/settlement/index?order_no=" + data.order_no;
      content= CryptoJS.AES.encrypt(content,app.globalData.AES_KEY,{
        iv:app.globalData.AES_IV,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }).toString();

      drawQrcode({
        width: 200,
        height: 200,
        canvasId: 'myQrcode',
        text: content,
        _this: this
      })
      this.setData({
        qrCodeVisible: true
      })

    } else {
      wx.showModal({
        title: '线下结算', // 可选，弹窗标题
        content: '请确认用户是否已经结算完毕', // 必填，弹窗内容
        showCancel: true, // 可选，是否显示取消按钮，默认为 true
        cancelText: '取消', // 可选，取消按钮文字，默认为"取消"
        cancelColor: '#000000', // 可选，取消按钮的文字颜色，默认为"#000000"
        confirmText: '确定', // 可选，确认按钮文字，默认为"确定"
        confirmColor: '#3CC51F', // 可选，确认按钮的文字颜色，默认为"#3CC51F"
        success: (res1) => {
          if (res1.cancel) {
            return;
          } else if (res1.confirm) {
            // 用户点击了确认按钮
            WXAPI.payOrderOutline(data.order_no).then(res => {
              if (res.code == 200) {
                clearInterval(this.data.interval);
                Toast({
                  context: this,
                  selector: '#t-toast',
                  message: "线下支付订单更新成功",
                  theme: 'success',
                  direction: 'column',
                });
                return
              }
              Toast({
                context: this,
                selector: '#t-toast',
                message: (res.mesasge || res.msg),
                theme: 'warning',
                direction: 'column',
              });

            })
          }
        }
      })



    }
  },
  openCouponList() {
    this.setData({
      couponVisible: true
    })
  },
  payByUser() {

    var data = this.data.orderDetail
    var coupon_id = this.data.selectedCoupon == {} ? null : this.data.selectedCoupon.id
    var param = {}
    if (coupon_id != null) {
      param.coupon_id = coupon_id
    }
    debugger
    param.payment_method = this.data.useRecharge ? 4 : 1
    WXAPI.payOrderOnline(data.order_no, param).then(res => {
      if (res.code == 200) {
        var payment = res.data;

        if (payment) {
          // 判断是不是微信支付
          wx.requestPayment({
            appid: payment.appid,
            timeStamp: payment.timeStamp,
            nonceStr: payment.nonceStr,
            package: payment.package,
            signType: payment.signType,
            paySign: payment.paySign,
            success: (res) => {
              wx.showToast({
                "title": "结算成功"
              });
            },
            fail: (res) => {
              console.log(res)
              wx.showToast({
                icon:"none",
                "title": "支付取消"
              });
              clearInterval(this.data.interval)
            }
          });
        }

        var interval = setInterval(() => {
          WXAPI.queryOrderByNo(data.order_no).then(res => {
            if (res.status == 2) {
              clearInterval(this.data.interval)
              this.queryCurrentOrder(data.order_no);
            }
          })
        }, 1000)
        this.setData({
          interval
        })
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: (res.mesasge || res.msg),
          theme: 'warning',
          direction: 'column',
        });
      }

    })
  },
  onPullDownRefresh() {

    this.queryOrder(this.data.payStatus, () => {
      this.setData({
        'baseRefresh.value': false
      })
    });

  },
  onScroll(e) {
    const { scrollTop } = e.detail;

    this.setData({
      backTopVisible: scrollTop > 100,
    });
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    this.setData({
      userInfo: wx.getStorageSync("userInfo")
    })
    this.queryCurrentOrder(e.order_no);

    if (this.data.userInfo.admin) {
      // var content="/pages/settlement/index?order_no="+e.order_no;
      // drawQrcode({
      //   width: 200,
      //   height: 200,
      //   canvasId: 'myQrcode2',
      //   text: content,
      //   _this: this
      // })
     
    } else {
      //不是管理员扫码默认来付钱的
      this.queryCanUseCoupon();
    }
  },
  queryCurrentOrder(order_no) {

    WXAPI.queryOrderByNo(order_no).then(res => {

      var orderDetail = res;
      orderDetail.payment_time = dateUtil.toDate(orderDetail.payment_time);
      orderDetail.order_time = dateUtil.toDate(orderDetail.order_time);
      this.calculateAmount(orderDetail);
    })
  },
   calculateAmount(orderDetail,coupon_id){
    WXAPI.calculateAmount(orderDetail.order_no,coupon_id).then(res => {
      orderDetail.real_amount=res.data;
      this.setData({
        orderDetail
      })
      this.setData({
        useRecharge : this.data.userInfo.recharge_balance > this.data.orderDetail.origin_amount,
      })
    });
  },
  showCouponsList() {
    this.setData({
      couponVisible: true,
    })
  },
  closeCouponListPop() {
    this.setData({
      couponVisible: false,
    })
  },
  closeQrCode() {
    this.setData({
      qrCodeVisible: false
    })
  },
  confirmCoupon() {
    // 把选中的券名字显示在上面
    var { selectedCoupon } = this.data;
    if (selectedCoupon) {
      this.setData({
        use_coupon: selectedCoupon.coupon_name,
        confirmCoupon: selectedCoupon,
        couponVisible: false,
        visible: true
      })
      this.calculateAmount(this.data.orderDetail,selectedCoupon.coupon_id)
    } else {
      this.setData({
        use_coupon: '',
        confirmCoupon: null,
        couponVisible: false,
        visible: true
      })
      this.calculateAmount(this.data.orderDetail)

    }
  },
  onSelectCoupon(e) {
    const data = e.currentTarget.dataset.data;
    if(data.is_not_valid){
      wx.showToast({
        "title":"当前卡券不可用"
      });
      return;
    }

    if (this.data.selectedCoupon && data.id == this.data.selectedCoupon.id) {
      //取消
      this.setData({
        selectedCoupon: null
      });
      return;
    }
    this.setData({
      selectedCoupon: data
    });
  },
  queryCanUseCoupon() {

    let { coupons_current_no, coupons_page_size, isLastPage } = this.data;
    let _canUseCoupons = this.data.canUseCoupons

    if (isLastPage) {
      return;
    }
    //venue==2 机位结算
    WXAPI.queryCouponsByUser(this.data.userInfo.id, {
      "payment_venue": 2, "status": 1,
      "current_no": coupons_current_no,
      "page_size": coupons_page_size
    }).then(res => {

      var canUseCoupons = res;
      if (!canUseCoupons || canUseCoupons.length == 0) {
        this.setData({
          isLastPage: true
        })
        return;
      }
      canUseCoupons.forEach(item => {
        item.expire_time = dateUtil.toDate(item.expire_time)
        item.use_time = dateUtil.toDate(item.use_time)
        item.is_not_valid=dateUtil.compare(item.start_time,new Date());
        item.start_time = dateUtil.toDate(item.start_time)
      })
      if (_canUseCoupons != undefined && _canUseCoupons.length > 0)
        _canUseCoupons = _canUseCoupons.concat(canUseCoupons)
      else
        _canUseCoupons = canUseCoupons

      this.setData({
        canUseCoupons: _canUseCoupons
      })

    })
  },
  loadMoreCoupons() {
    let { coupons_current_no, coupons_page_size } = this.data;
    this.setData({
      coupons_current_no: coupons_current_no + coupons_page_size
    })
    this.queryCanUseCoupon();
  },
  useRecharge(event){
    this.setData({
      useRecharge:event.detail,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.interval);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})